<template>
  <view class="patient-edit-page">
    <view class="page-header">
      <text class="page-title">编辑患者档案</text>
      <view class="header-actions">
        <button class="btn btn-default" @click="handleCancel">取消</button>
        <button class="btn btn-primary" @click="handleSubmit">保存</button>
      </view>
    </view>

    <view v-if="loading" class="loading-container">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载中...</text>
    </view>

    <view v-else class="form-content">
      <view class="form-card">
        <view class="card-header">
          <text class="card-title">基本信息</text>
        </view>
        <view class="card-body">
          <view class="form-item">
            <text class="label">性别</text>
            <view class="readonly-field-inline">{{ genderOptions[genderIndex]?.label || '未设置' }}</view>
          </view>
          
          <view class="form-item">
            <text class="label">出生日期</text>
            <view class="readonly-field-inline">{{ birthDateStr || '未设置' }}</view>
          </view>
          
          <view class="form-item">
            <text class="label">身份证号</text>
            <view class="readonly-field-inline">{{ formData.id_card || '未设置' }}</view>
          </view>
          
          <view class="form-item form-item-readonly">
            <text class="label">患者联系电话</text>
            <view class="readonly-wrapper">
              <view class="phone-with-badge">
                <view class="readonly-field">{{ formData.mobile || '未设置' }}</view>
                <view v-if="formData.mobile" :class="['verify-badge', formData.mobile_confirmed === 1 ? 'verified' : 'unverified']">
                  {{ formData.mobile_confirmed === 1 ? '已认证' : '未认证' }}
                </view>
              </view>
              <text class="field-tip">（只读，需在用户端修改）</text>
            </view>
          </view>
          
          <view class="form-item">
            <text class="label">血型</text>
            <picker mode="selector" :range="bloodTypeOptions" :value="bloodTypeIndex" @change="handleBloodTypeChange">
              <view class="picker-input">{{ bloodTypeOptions[bloodTypeIndex] || '请选择' }}</view>
            </picker>
          </view>
        </view>
      </view>

      <view class="form-card">
        <view class="card-header">
          <text class="card-title">医疗信息</text>
        </view>
        <view class="card-body">
          <view class="form-item">
            <text class="label">过敏史</text>
            <input 
              v-model="allergiesStr" 
              class="input" 
              placeholder="多个过敏源用逗号分隔，例如：青霉素、海鲜" 
              @focus="handleInputFocus"
              @blur="handleInputBlur"
            />
          </view>
          
          <view class="form-item">
            <text class="label">慢性病史</text>
            <input 
              v-model="chronicDiseasesStr" 
              class="input" 
              placeholder="多个病史用逗号分隔，例如：高血压、糖尿病" 
              @focus="handleInputFocus"
              @blur="handleInputBlur"
            />
          </view>
        </view>
      </view>

      <view class="form-card">
        <view class="card-header">
          <text class="card-title">紧急联系人</text>
        </view>
        <view class="card-body">
          <view class="form-item">
            <text class="label">联系人姓名</text>
            <input 
              v-model="formData.emergency_contact" 
              class="input" 
              placeholder="请输入联系人姓名" 
              @focus="handleInputFocus"
              @blur="handleInputBlur"
            />
          </view>
          
          <view class="form-item">
            <text class="label">联系人电话</text>
            <input 
              v-model="formData.emergency_phone" 
              class="input" 
              type="number" 
              placeholder="请输入联系电话" 
              @focus="handleInputFocus"
              @blur="handleInputBlur"
            />
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'

const loading = ref(true)
const patientId = ref('')

const genderOptions = [
  { label: '未知', value: 0 },
  { label: '男', value: 1 },
  { label: '女', value: 2 }
]
const bloodTypeOptions = ['', 'A型', 'B型', 'AB型', 'O型', 'RH阴性A型', 'RH阴性B型', 'RH阴性AB型', 'RH阴性O型']

const formData = reactive({
  gender: 0,
  birth_date: null,
  id_card: '',
  mobile: '',
  mobile_confirmed: 0,
  blood_type: '',
  allergies: [],
  chronic_diseases: [],
  emergency_contact: '',
  emergency_phone: ''
})

const genderIndex = ref(0)
const bloodTypeIndex = ref(0)
const birthDateStr = ref('')
const allergiesStr = ref('')
const chronicDiseasesStr = ref('')

onMounted(async () => {
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  patientId.value = currentPage.options.id || ''
  
  if (!patientId.value) {
    uni.showToast({ title: '缺少患者ID', icon: 'none' })
    setTimeout(() => {
      uni.redirectTo({ url: '/pages/business/patients/list' })
    }, 1500)
    return
  }
  
  await loadPatientData()
  loading.value = false
})

async function loadPatientData() {
  try {
    const dhPatients = uniCloud.importObject('dh-patients')
    const result = await dhPatients.getPatientById(patientId.value)
    
    if (result.code === 200 && result.data) {
      formData.gender = result.data.gender || 0
      formData.birth_date = result.data.birth_date || null
      formData.id_card = result.data.id_card || ''
      formData.mobile = result.data.mobile || ''
      formData.mobile_confirmed = result.data.mobile_confirmed || 0
      formData.blood_type = result.data.blood_type || ''
      formData.allergies = result.data.allergies || []
      formData.chronic_diseases = result.data.chronic_diseases || []
      formData.emergency_contact = result.data.emergency_contact || ''
      formData.emergency_phone = result.data.emergency_phone || ''
      
      // 设置界面显示
      genderIndex.value = genderOptions.findIndex(g => g.value === formData.gender)
      if (genderIndex.value === -1) genderIndex.value = 0
      
      if (formData.birth_date) {
        const date = new Date(formData.birth_date)
        birthDateStr.value = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
      }
      
      bloodTypeIndex.value = bloodTypeOptions.indexOf(formData.blood_type)
      if (bloodTypeIndex.value === -1) bloodTypeIndex.value = 0
      
      allergiesStr.value = formData.allergies.join('，')
      chronicDiseasesStr.value = formData.chronic_diseases.join('，')
    } else {
      throw new Error(result.message || '患者不存在')
    }
  } catch (err) {
    console.error('加载患者数据失败:', err)
    uni.showToast({ title: err.message || '加载失败', icon: 'none' })
    setTimeout(() => {
      uni.redirectTo({ url: '/pages/business/patients/list' })
    }, 1500)
  }
}

function handleGenderChange(e) {
  genderIndex.value = parseInt(e.detail.value)
  formData.gender = genderOptions[genderIndex.value].value
}

function handleBirthDateChange(e) {
  birthDateStr.value = e.detail.value
  formData.birth_date = new Date(e.detail.value).getTime()
}

function handleBloodTypeChange(e) {
  bloodTypeIndex.value = parseInt(e.detail.value)
  formData.blood_type = bloodTypeOptions[bloodTypeIndex.value]
}

function handleInputFocus(e) {
  // 输入框获得焦点时的处理（如果需要可以添加逻辑）
  // uni-app的input组件在获得焦点时会自动处理placeholder
}

function handleInputBlur(e) {
  // 输入框失去焦点时的处理
}

function handleCancel() {
  uni.redirectTo({ url: '/pages/business/patients/list' })
}

async function handleSubmit() {
  // 处理数组字段
  formData.allergies = allergiesStr.value ? allergiesStr.value.split(/[,，]/).map(s => s.trim()).filter(Boolean) : []
  formData.chronic_diseases = chronicDiseasesStr.value ? chronicDiseasesStr.value.split(/[,，]/).map(s => s.trim()).filter(Boolean) : []
  
  try {
    uni.showLoading({ title: '保存中...' })
    const dhPatients = uniCloud.importObject('dh-patients')
    const result = await dhPatients.updatePatient(patientId.value, formData)
    uni.hideLoading()
    
    if (result.code === 200) {
      uni.showToast({ title: '更新成功', icon: 'success' })
      setTimeout(() => {
        uni.redirectTo({ url: '/pages/business/patients/list' })
      }, 1500)
    } else {
      uni.showToast({ title: result.message || '更新失败', icon: 'none' })
    }
  } catch (err) {
    console.error('更新失败:', err)
    uni.hideLoading()
    uni.showToast({ title: err.message || '更新失败', icon: 'none' })
  }
}
</script>

<style lang="scss" scoped>
.patient-edit-page {
  min-height: 100vh;
  background: #f5f5f5;
}

.page-header {
  background: #fff;
  padding: 30rpx 40rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  border-bottom: 1rpx solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 20rpx;
}

.page-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 16rpx;
}

.btn {
  padding: 12rpx 24rpx;
  font-size: 28rpx;
  border-radius: 8rpx;
  border: none;
  white-space: nowrap;
  min-width: 100rpx;
  text-align: center;
  
  &.btn-default {
    background: #f5f5f5;
    color: #666;
  }
  
  &.btn-primary {
    background: #007aff;
    color: #fff;
  }
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 200rpx 0;
}

.loading-spinner {
  width: 80rpx;
  height: 80rpx;
  border: 6rpx solid #f3f3f3;
  border-top: 6rpx solid #007aff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 30rpx;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 28rpx;
  color: #666;
}

.form-content {
  padding: 20rpx;
}

.form-card {
  background: #fff;
  border-radius: 8rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
  margin-bottom: 20rpx;
}

.card-header {
  background: #fafafa;
  padding: 24rpx 32rpx;
  border-bottom: 1rpx solid #e0e0e0;
}

.card-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.card-body {
  padding: 32rpx;
}

.form-item {
  display: flex;
  align-items: center;
  margin-bottom: 32rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  &.form-item-readonly {
    flex-direction: column;
    align-items: flex-start;
  }
}

.label {
  font-size: 28rpx;
  color: #333;
  min-width: 180rpx;
  
  .form-item-readonly & {
    margin-bottom: 12rpx;
    min-width: auto;
  }
}

.input {
  flex: 1;
  padding: 16rpx 24rpx;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
  font-size: 28rpx;
  background: #fff;
  box-sizing: border-box;
  min-width: 0;
  width: 100%;
  min-height: 80rpx;
  line-height: 48rpx;
  
  &:focus {
    border-color: #007aff;
    background: #f9fbff;
  }
  
  &::placeholder {
    color: #999;
    font-size: 26rpx;
  }
}

.picker-input {
  flex: 1;
  padding: 16rpx 24rpx;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
  font-size: 28rpx;
  background: #fff;
  color: #333;
  box-sizing: border-box;
  min-width: 0;
  min-height: 80rpx;
  line-height: 48rpx;
  display: flex;
  align-items: center;
}

.readonly-wrapper {
  width: 100%;
}

.readonly-field {
  padding: 16rpx 24rpx;
  border: 1rpx solid #e8e8e8;
  border-radius: 8rpx;
  font-size: 28rpx;
  background: #f5f5f5;
  color: #666;
  box-sizing: border-box;
}

.readonly-field-inline {
  flex: 1;
  padding: 16rpx 24rpx;
  border: 1rpx solid #e8e8e8;
  border-radius: 8rpx;
  font-size: 28rpx;
  background: #f5f5f5;
  color: #666;
  box-sizing: border-box;
  min-height: 68rpx;
  display: flex;
  align-items: center;
}

.field-tip {
  font-size: 24rpx;
  color: #999;
  margin-top: 8rpx;
}

.phone-with-badge {
  display: flex;
  align-items: center;
  gap: 12rpx;
  
  .readonly-field {
    flex: 1;
  }
}

.verify-badge {
  padding: 6rpx 16rpx;
  border-radius: 6rpx;
  font-size: 24rpx;
  font-weight: 500;
  white-space: nowrap;
  
  &.verified {
    background: #d1fae5;
    color: #065f46;
  }
  
  &.unverified {
    background: #fee2e2;
    color: #991b1b;
  }
}
</style>

